<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="listDictApi">
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" v-auth="['system:dict:add']" @click="openDialog(1, '字典类型新增')">新增</el-button>
        <el-button type="primary" v-auth="['system:dict:export']" icon="Download" plain @click="downloadFile">导出</el-button>
        <el-button
          type="danger"
          v-auth="['system:user:remove']"
          icon="Delete"
          plain
          :disabled="!scope.isSelected"
          @click="batchDelete(scope.selectedListIds)"
        >
          批量删除
        </el-button>
        <el-button type="danger" v-auth="['system:config:remove']" icon="Refresh" plain @click="handleRefreshCache"> 刷新缓存 </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link icon="EditPen" v-auth="['system:dict:edit']" @click="openDialog(2, '字典类型编辑', scope.row)">
          编辑
        </el-button>
        <el-button type="primary" link icon="Delete" v-auth="['system:dict:remove']" @click="deleteDict(scope.row)"> 删除 </el-button>
      </template>
    </ProTable>
    <FormDialog ref="formDialogRef" :items-options="itemsOptions" :model="model" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="Dict">
import { useHandleData } from '@/hooks/useHandleData'
import { useDownload } from '@/hooks/useDownload'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDictStore } from '@/stores/modules/dict'
import ImportExcel from '@/components/ImportExcel/index.vue'
import FormDialog from '@/components/FormDialog/index.vue'
import { ProTableInstance, ColumnProps } from '@/components/ProTable/interface'
import { listDictApi, delDictApi, addDictApi, updateDictApi, exportApi, getDictApi, refreshCacheApi } from '@/api/modules/system/dict'

// ProTable 实例
const proTable = ref<ProTableInstance>()
// 表单model
const model = ref({})
// 删除用户信息
const deleteDict = async (params: any) => {
  await useHandleData(delDictApi, params.dictId, `删除【${params.dictName}】字典类型`)
  proTable.value?.getTableList()
}

// 批量删除用户信息
const batchDelete = async (ids: string[]) => {
  await useHandleData(delDictApi, ids, '删除所选字典类型信息')
  proTable.value?.clearSelection()
  proTable.value?.getTableList()
}

// 导出用户列表
const downloadFile = async () => {
  ElMessageBox.confirm('确认导出字典类型数据?', '温馨提示', { type: 'warning' }).then(() =>
    useDownload(exportApi, '字典类型列表', proTable.value?.searchParam)
  )
}

const formDialogRef = ref<InstanceType<typeof FormDialog> | null>(null)
// 打开弹框的功能
const openDialog = async (type: number, title: string, row?: any) => {
  let res = { data: {} }
  if (row?.dictId) {
    res = await getDictApi(row?.dictId || null)
  }
  model.value = type == 1 ? { version: 0 } : { ...res.data, version: 0 }
  setItemsOptions()
  const params = {
    title,
    width: 500,
    isEdit: type !== 3,
    api: type == 1 ? addDictApi : updateDictApi,
    getTableList: proTable.value?.getTableList
  }
  formDialogRef.value?.openDialog(params)
}

const router = useRouter()
// 跳转详情页
const toDetail = (row: { dictId: any }) => {
  router.push(`/system/dict-data/index/${row.dictId}`)
}

/** 刷新缓存按钮操作 */
const handleRefreshCache = async () => {
  await refreshCacheApi()
  ElMessage.success('刷新成功')
  useDictStore().cleanDict()
}

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  { type: 'selection', fixed: 'left', width: 60 },
  { prop: 'dictId', label: '字典编号', width: 100 },
  {
    prop: 'dictName',
    label: '字典名称',
    search: {
      el: 'input'
    },
    width: 120
  },
  {
    prop: 'dictType',
    label: '字典类型',
    search: {
      el: 'input'
    },
    render: scope => {
      return (
        <el-button type="primary" link onClick={() => toDetail(scope.row)}>
          {scope.row.dictType}
        </el-button>
      )
    },
    width: 150
  },
  {
    prop: 'createTime',
    label: '创建时间'
  },
  {
    prop: 'remark',
    label: '备注',
    search: {
      el: 'input'
    }
  },
  { prop: 'operation', label: '操作', width: 230 }
])

// 表单配置项
let itemsOptions = reactive<ProForm.ItemsOptions[]>([])
const setItemsOptions = () => {
  itemsOptions = [
    {
      label: '字典名称',
      prop: 'dictName',
      rules: [{ required: true, message: '字典名称不能为空', trigger: 'blur' }],
      compOptions: {
        placeholder: '请输入字典名称'
      }
    },
    {
      label: '字典类型',
      prop: 'dictType',
      rules: [{ required: true, message: '字典类型不能为空', trigger: 'blur' }],
      compOptions: {
        placeholder: '请输入字典类型'
      }
    },
    {
      label: '备注',
      prop: 'remark',
      compOptions: {
        type: 'textarea',
        placeholder: '请输入备注'
      }
    }
  ]
}
</script>
